/*
 * UART_test.c
 *
 * Created: 2013-12-10 11:14:55
 *  Author: Mattias
 */ 

#define F_CPU 2000000UL
#define BAUDRATE 9600
#define BLINK_DELAY_MS 1000
#include <util/delay.h>
#include <avr/io.h>
void USART_Init(unsigned int bsel);
void USART_Transmit(unsigned char data);
char USART_Recieve(void);
//(1/(16*(((F_CPU)/Baudrate)-1)
int main (void) {
	PORTE.DIRSET = 0b11110111 ; // Set all pins on port A to be output.
	PORTC.DIRSET = PIN3_bm; // (TXD1) as output.
	PORTC.SET    = PIN3_bm; // (TXD1) as high. */
	PORTC.DIRCLR = PIN2_bm; // (RXD1) as input.

	int baud = 1/(16*(((F_CPU)/BAUDRATE)-1));
	USART_Init(baud);
	 // Set pin 0 to be output
	
	
	
		 //

		char byte = USART_Recieve();
		if(byte == 'a'){
			PORTE.OUT = 0b11110000;	
		}
		if(byte == 'b'){
			PORTE.OUT = 0b00001111;	
		}
	
}

void USART_Init(unsigned int bsel)
{
	/* Set baud rate */
	USARTC0.BAUDCTRLB = (unsigned char)(bsel>>8);
	USARTC0.BAUDCTRLA = (unsigned char)bsel;
	
	/* Set frame format: 8data, 1 stop bit */
	USARTC0.CTRLC = (USARTC0.CTRLC & ~USART_CHSIZE_gm) | USART_CHSIZE_8BIT_gc;

	/* Enable receiver and transmitter */
	USARTC0.CTRLB = (USART_RXEN_bm | USART_TXEN_bm);
}

void USART_Transmit(unsigned char data)
{
	while ( !( USARTC0.STATUS & USART_DREIF_bm) );
	USARTC0.DATA = data;
}
char USART_Recieve(void)
{
	char recievedByte;
	while( !(USART_RXEN_bm));
	recievedByte = USARTC0.DATA;
	return recievedByte;
}